<template>
  <div>
    <el-dialog
      v-model="visible"
      :title="isEdit ? '编辑任务' : '添加任务'"
      width="1000px"
      :before-close="handleClose"
      destroy-on-close
    >
      <el-form
        ref="taskFormRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="任务描述" prop="description">
          <div class="markdown-editor-container">
            <MdEditor
              v-model="formData.description"
              :height="300"
              :preview="true"
              :toolbars="toolbars"
              :upload-image="handleUploadImage"
              placeholder="请输入任务描述..."
            />
          </div>
        </el-form-item>

        <el-form-item label="责任人" prop="assignedTo">
          <el-select
            v-model="formData.assignedTo"
            placeholder="请选择责任人"
            style="width: 100%"
            filterable
            clearable
          >
            <el-option
              v-for="member in projectMembers"
              :key="member.userId"
              :label="`${member.name} (${member.account})`"
              :value="member.userId"
            >
              <div class="member-option">
                <span class="member-name">{{ member.name }}</span>
                <span class="member-account">{{ member.account }}</span>
                <span v-if="member.deptName" class="member-dept">{{ member.deptName }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="beginDate">
              <el-date-picker
                v-model="formData.beginDate"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="dueDate">
              <el-date-picker
                v-model="formData.dueDate"
                type="datetime"
                placeholder="选择结束时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item v-if="isEdit" label="任务状态">
          <el-radio-group v-model="formData.status">
            <el-radio :value="0">进行中</el-radio>
            <el-radio :value="1">已完成</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmit">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { MdEditor, type ToolbarNames } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import type { FormInstance, FormRules } from 'element-plus'
import { createTask, updateTask, type CreateTaskRequest, type UpdateTaskRequest, type ProjectTask } from '../api/task'
import { getProjectMembers, type ProjectMember } from '../api/projectMember'

interface Props {
  modelValue: boolean
  projectId: number
  taskData?: ProjectTask | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  taskData: null
})

const emit = defineEmits<Emits>()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.taskData)
const loading = ref(false)
const taskFormRef = ref<FormInstance>()
const projectMembers = ref<ProjectMember[]>([])

// 表单数据
const formData = reactive({
  description: '',
  assignedTo: null as number | null,
  beginDate: '',
  dueDate: '',
  status: 0
})

// 表单验证规则
const formRules: FormRules = {
  description: [
    { required: true, message: '请输入任务描述', trigger: 'blur' },
    { min: 1, message: '任务描述不能为空', trigger: 'blur' }
  ],
  assignedTo: [
    { required: true, message: '请选择责任人', trigger: 'change' }
  ],
  beginDate: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  dueDate: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// Markdown编辑器工具栏配置
const toolbars: ToolbarNames[] = [
  'bold',
  'underline',
  'italic',
  'strikeThrough',
  'sub',
  'sup',
  'quote',
  'unorderedList',
  'orderedList',
  'task',
  'codeRow',
  'code',
  'link',
  'image',
  'table',
  'mermaid',
  'katex',
  'revoke',
  'next',
  'save',
  'pageFullscreen',
  'fullscreen',
  'preview',
  'htmlPreview',
  'catalog'
]

// 图片上传处理
const handleUploadImage = async (file: File, callback: (url: string) => void) => {
  try {
    // 这里需要实现图片上传逻辑
    // 暂时使用本地预览
    const reader = new FileReader()
    reader.onload = (e) => {
      const result = e.target?.result as string
      callback(result)
    }
    reader.readAsDataURL(file)
    
    ElMessage.success('图片上传成功')
  } catch (error) {
    ElMessage.error('图片上传失败')
    console.error('图片上传失败:', error)
  }
}

// 禁用日期（结束时间不能早于开始时间）
const disabledDate = (time: Date) => {
  if (formData.beginDate) {
    const beginDate = new Date(formData.beginDate)
    return time.getTime() < beginDate.getTime()
  }
  return false
}

// 获取项目成员列表
const fetchProjectMembers = async () => {
  try {
    const response = await getProjectMembers(props.projectId)
    if (response.code === 200) {
      projectMembers.value = response.data || []
    }
  } catch (error) {
    console.error('获取项目成员失败:', error)
    ElMessage.error('获取项目成员失败')
  }
}

// 初始化表单数据
const initFormData = () => {
  if (props.taskData) {
    formData.description = props.taskData.description || ''
    formData.assignedTo = props.taskData.assignedTo || null
    formData.beginDate = props.taskData.beginDate || ''
    formData.dueDate = props.taskData.dueDate || ''
    formData.status = props.taskData.status || 0
  } else {
    // 重置表单
    Object.assign(formData, {
      description: '',
      assignedTo: null,
      beginDate: '',
      dueDate: '',
      status: 0
    })
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!taskFormRef.value) return
  
  try {
    await taskFormRef.value.validate()
    
    // 验证必填字段
    if (!formData.assignedTo) {
      ElMessage.error('请选择责任人')
      return
    }
    
    if (!formData.beginDate || !formData.dueDate) {
      ElMessage.error('请选择开始时间和结束时间')
      return
    }
    
    loading.value = true

    if (isEdit.value && props.taskData) {
      // 更新任务
      const updateData: UpdateTaskRequest = {
        id: props.taskData.id,
        description: formData.description,
        assignedTo: formData.assignedTo,
        beginDate: formData.beginDate,
        dueDate: formData.dueDate,
        status: formData.status
      }
      
      console.log('更新任务数据:', updateData) // 调试日志
      
      const response = await updateTask(updateData)
      if (response.code === 200) {
        ElMessage.success('任务更新成功')
        emit('success')
        handleClose()
      } else {
        ElMessage.error(response.message || '任务更新失败')
      }
    } else {
      // 创建任务
      const createData: CreateTaskRequest = {
        projectId: props.projectId,
        description: formData.description,
        assignedTo: formData.assignedTo,
        beginDate: formData.beginDate,
        dueDate: formData.dueDate
      }
      
      console.log('创建任务数据:', createData) // 调试日志
      console.log('日期格式检查:', {
        beginDate: formData.beginDate,
        dueDate: formData.dueDate,
        beginDateType: typeof formData.beginDate,
        dueDateType: typeof formData.dueDate
      })
      
      const response = await createTask(createData)
      if (response.code === 200) {
        ElMessage.success('任务创建成功')
        emit('success')
        handleClose()
      } else {
        ElMessage.error(response.message || '任务创建失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 监听对话框显示状态
watch(visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      initFormData()
      fetchProjectMembers()
    })
  }
})
</script>

<style scoped>
.markdown-editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.member-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.member-name {
  font-weight: 500;
}

.member-account {
  color: #909399;
  font-size: 12px;
}

.member-dept {
  color: #67c23a;
  font-size: 12px;
  background: #f0f9ff;
  padding: 2px 6px;
  border-radius: 2px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.md-editor) {
  border: none;
}

:deep(.md-editor-toolbar) {
  border-bottom: 1px solid #e4e7ed;
}

:deep(.md-editor-preview) {
  background-color: #fafafa;
}
</style>